<?php

namespace app\common\util;

use app\common\logic\PayLogic;
use app\common\model\trSystemSet;
use think\facade\Log;

class WxNotify
{
    /*
     * 服务器点对点
     * 该方法不能判断其它的，比如登录状态，不然会跳到其它地方，导致不能改变订单信息
     */
    public function handleNotify()
    {
        if(request()->server("IS_SCF")) {
            $xml = request()->param("xml");
        }else {
            $xml = file_get_contents('php://input');
        }
        $data = $this->fromXml($xml);
        if ($data['result_code'] != 'SUCCESS' || $data['return_code'] != 'SUCCESS') {
            $result = array(
                'return_code' => 'FAIL',
                'return_msg' => empty($data['return_msg']) ? $data['err_code_des'] : $data['return_msg']
            );
            return $this->toXml($result);
        }
        $payment_id = $data['out_trade_no']; //商户系统的订单号，与请求一致。
        // 因为改成Saas了，所以这块注释掉
//        $config = trSystemSet::getValue("wxAppConfig");
//        $key = $config["paySecret"];
//        $sign = $this->makeSign($data, $key);
//        if($data['sign'] != $sign){
//            $result = array(
//                'return_code' => 'FAIL',
//                'return_msg' => ""
//            );
//            return $this->toXml($result);
//        }
        if (!array_key_exists("transaction_id", $data)) {
            $result = array(
                'return_code' => 'FAIL',
                'return_msg' => "transaction_id参数不存在"
            );
            return $this->toXml($result);
        }

        $tradeData = array(
            'notifyTime' => $data['time_end'], //标准时间格式
            'totalFee' => $data['total_fee'] / 100,
            'tradeNo' => $data["transaction_id"],//支付宝交易号
            'account' => $data['mch_id'],
            'payAccount' => $data['openid'],//购买人openid
        );
        $payLogic = new PayLogic();
        $res = $payLogic->update_pay_status($payment_id, $tradeData); // 修改订单支付状态
        if($res) {
            $result = array(
                'return_code' => 'SUCCESS',
                'return_msg' => "OK"
            );
        }else{
            $result = array(
                'return_code' => 'FAIL',
                'return_msg' => ""
            );
        }
        return $this->toXml($result);
    }

    /**
     * @param $values
     * @param $key
     * @return string
     * 生成签名
     */
    public function makeSign($values, $key)
    {
        //签名步骤一：按字典序排序参数
        ksort($values);
        $string = $this->ToUrlParams($values);
        //签名步骤二：在string后加入KEY
        $string = $string . "&key=". $key;
        //签名步骤三：MD5加密
        $string = md5($string);
        //签名步骤四：所有字符转为大写
        $result = strtoupper($string);
        return $result;
    }

    /**
     * 格式化参数格式化成url参数
     */
    public function ToUrlParams($values)
    {
        $buff = "";
        foreach ($values as $k => $v)
        {
            if($k != "sign" && $v != "" && !is_array($v)){
                $buff .= $k . "=" . $v . "&";
            }
        }

        $buff = trim($buff, "&");
        return $buff;
    }

    /**
     * @param $xml
     * @return mixed
     * @throws Exception
     * 将xml转为array
     */
    public function fromXml($xml)
    {
        if(!$xml){
            Log::write("支付回调解析xml：xml数据异常或者为空");
            return false;
        }
        //将XML转为array
        //禁止引用外部xml实体
        libxml_disable_entity_loader(true);
        $values = json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
        return $values;
    }

    /**
     * 输出xml字符
     **/
    public function toXml($values)
    {
        if(!is_array($values)
            || count($values) <= 0)
        {
            return false;
        }

        $xml = "<xml>";
        foreach ($values as $key=>$val)
        {
            if (is_numeric($val)){
                $xml.="<".$key.">".$val."</".$key.">";
            }else{
                $xml.="<".$key."><![CDATA[".$val."]]></".$key.">";
            }
        }
        $xml.="</xml>";
        return $xml;
    }
}